#include "codedelegate.h"
#include "tab2dialog.h"
#include "ui_tab2dialog.h"

#include <QDir>
#include <QFile>
#include <QFileDialog>
#include <QMessageBox>
#include <QSettings>
#include <QTextStream>

tab2Dialog::tab2Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::tab2Dialog)
{
    ui->setupUi(this);
    /*
    ui->AddButton_2->setStyleSheet("background-color:rgba(214,214,214,214);");
    ui->exportButton_2->setStyleSheet("background-color:rgba(214,214,214,214);");
    ui->cleanButton_2->setStyleSheet("background-color:rgba(214,214,214,214);");
    ui->cleanallButton_2->setStyleSheet("background-color:rgba(214,214,214,214);");
    ui->importButton_2->setStyleSheet("background-color:rgba(214,214,214,214);");
*/
    QRegExp regExp("[a-fA-F0-9]{2}\\s{0,1}[a-fA-F0-9]{2}\\s{0,1}[a-fA-F0-9]{2}\\s{0,1}[a-fA-F0-9]{2}");
    ui->lineEdit_3->setValidator(new QRegExpValidator(regExp, this));

    ui->AddButton_2->setDefault(1);

    QSettings settings;

    settings.beginGroup("BID");
    QStringList table_keys=settings.allKeys();
    ui->tableWidget->setColumnCount(2);
    QStringList headerText;
    headerText << tr("code") << tr("description");
    ui->tableWidget->setHorizontalHeaderLabels(headerText);
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Interactive);

    ui->tableWidget->setEditTriggers(QAbstractItemView::DoubleClicked);
    ui->tableWidget->setShowGrid(true);
    ui->tableWidget->verticalHeader()->hide();

    ui->tableWidget->setItemDelegateForColumn(0, new codeDelegate(this));

    for(int i=0;i<table_keys.count();i++){
        ui->tableWidget->insertRow(ui->tableWidget->rowCount());

        ui->tableWidget->setItem(i,0,new QTableWidgetItem(space_str(table_keys[i])));
        ui->tableWidget->setItem(i,1,new QTableWidgetItem(settings.value(table_keys[i]).toString()));
    }
    settings.endGroup();
}

tab2Dialog::~tab2Dialog()
{
    delete ui;
}

QString tab2Dialog::space_str(const QString &orig)
{
    return QString("%1 %2 %3 %4").arg(orig.left(2)).arg(orig.mid(2, 2)).arg(orig.mid(4,2)).arg(orig.right(2));
}

void tab2Dialog::savedata()
{
    QSettings Setting;
    Setting.remove("BID");
    int row_count = ui->tableWidget->rowCount();
    for(int i=0;i<row_count;i++){
        QString parent_code = ui->tableWidget->item(i,0)->text();
        parent_code.remove(QRegExp("\\s"));
        QString parent_key = "BID/"+parent_code;
        QString parent_value = ui->tableWidget->item(i,1)->text();
        Setting.setValue(parent_key,parent_value);
    }
}

void tab2Dialog::on_importButton_2_clicked()
{
    QString name = QFileDialog::getOpenFileName(this);
    QFile file(name);
     if(file.open(QIODevice::ReadOnly | QIODevice::Text)){
         QStringList list;
         list.clear();
         QTextStream in(&file);
         int i =0,flag=0;
         while(!in.atEnd()){
             QString fileLine = in.readLine();
             list = fileLine.split(",", QString::SkipEmptyParts);
             if(i>0){
                 int row_count = ui->tableWidget->rowCount();
                 int num =0;
                 for(int j=0;j<row_count;j++){
                     QString str_code;
                     QString str_description;

                     str_code = ui->tableWidget->item(j,0)->text();
                     str_code.remove(QRegExp("\\s"));
                     str_description = ui->tableWidget->item(j,1)->text();

                     if(list.at(0) == str_code){
                         if(list.at(1) == str_description){
                             num=1;break;
                         }
                         else{
                             num=2;break;
                         }
                     }
                 }
                 if(num == 0){
                     ui->tableWidget->insertRow(row_count);
                     ui->tableWidget->setItem(row_count, 0, new QTableWidgetItem(space_str(list.at(0))));
                     ui->tableWidget->setItem(row_count, 1, new QTableWidgetItem(list.at(1)));
                 }

                 if(num == 2 && flag == 1){
                     ui->tableWidget->setItem(i-1, 1, new QTableWidgetItem(list.at(1)));
                 }
                 if(num == 2 && flag == 0){
                     QString warning = "The same code:"+list.at(0)+",cover or not?";
                     QMessageBox:: StandardButton result= QMessageBox::warning(NULL, "warning", warning, QMessageBox::Yes | QMessageBox::No | QMessageBox::YesAll | QMessageBox::NoAll);

                     switch (result) {
                     case QMessageBox::Yes:
                         ui->tableWidget->setItem(i-1, 1, new QTableWidgetItem(list.at(1)));
                         break;
                     case QMessageBox::No:

                         break;
                     case QMessageBox::YesAll:
                         ui->tableWidget->setItem(i-1, 1, new QTableWidgetItem(list.at(1)));
                         flag=1;
                         break;
                     case QMessageBox::NoAll:
                         flag=2;
                         break;
                     default:
                         break;
                     }
                 }
             }
             i++;
         }
     }
     file.close();
}


void tab2Dialog::on_exportButton_2_clicked()
{
    QString runPath = QDir::currentPath();
    QString file_name = QFileDialog::getSaveFileName(this,tr("export file"),runPath,"(*.csv)",0,QFileDialog::DontConfirmOverwrite);
    QFile file(file_name);
    bool ret = file.open(QIODevice::Truncate | QIODevice::ReadWrite);
    if(ret == true){
        QTextStream stream(&file);
        QString conTents;

        QHeaderView * header = ui->tableWidget->horizontalHeader() ;
        if (NULL != header){
            for (int i = 0; i < header->count(); i++){
                QTableWidgetItem *item = ui->tableWidget->horizontalHeaderItem(i);
                if (NULL != item){
                    conTents += item->text() + ",";
                }
            }
            conTents += "\n";
        }

        for (int row = 0; row < ui->tableWidget->rowCount(); row++){
            for (int column = 0; column < ui->tableWidget->columnCount(); column++){
                QTableWidgetItem* item = ui->tableWidget->item(row, column);
                if (NULL != item ){
                    QString str = item->text();
                    str.remove(QRegExp("\\s"));
                    str.replace(","," ");
                    conTents += str + ",";
                }
            }
            conTents += "\n";
        }
        stream << conTents;
        file.close();
    }
}


void tab2Dialog::on_cleanButton_2_clicked()
{
    QList<QTableWidgetSelectionRange>ranges=ui->tableWidget->selectedRanges();
    int count=ranges.count();
    for(int i=0;i<count;i++){
        int topRow=ranges.at(i).topRow();
        int bottomRow=ranges.at(i).bottomRow();
        for(int j=topRow;j<=bottomRow;j++)
        {
            int checkrow=j-i;
            ui->tableWidget->removeRow(checkrow);
        }
    }
}


void tab2Dialog::on_cleanallButton_2_clicked()
{
    for(int row = ui->tableWidget->rowCount() - 1;row >= 0; row--)
    {
        ui->tableWidget->removeRow(row);
    }
}


void tab2Dialog::on_AddButton_2_clicked()
{
    QString parent_code = ui->lineEdit_3->text();
    QString parent_value = ui->lineEdit_4->text();

    int num=0;
    if (!(parent_code.isEmpty())&&!(parent_value.isEmpty())){
        for(int i=0;i<ui->tableWidget->rowCount();i++)
        {
            if(ui->tableWidget->item(i,0)->text()==parent_code)
            {
                num++;
            }
        }
        if(num==0){
/*
            ui->lineEdit_3->clear();
            ui->lineEdit_4->clear();
*/
            parent_code.remove(QRegExp("\\s"));
            parent_code=space_str(parent_code);
            int row_count = ui->tableWidget->rowCount();
            ui->tableWidget->insertRow(row_count);
            ui->tableWidget->setItem(row_count,0,new QTableWidgetItem(parent_code));
            ui->tableWidget->setItem(row_count,1,new QTableWidgetItem(parent_value));
        }
    }
}


void tab2Dialog::on_lineEdit_4_returnPressed()
{
    on_AddButton_2_clicked();
}


void tab2Dialog::on_tableWidget_cellClicked(int row, int column)
{
    QTableWidgetItem* code_Item = ui->tableWidget->item(row,0);
    QTableWidgetItem* description_Item = ui->tableWidget->item(row,1);
    ui->lineEdit_3->setText(code_Item->text());
    ui->lineEdit_4->setText(description_Item->text());
}
